package com.lagou.edu.controller;

import com.lagou.edu.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping
    public String index(HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        return "login";
    }

    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();

        Boolean result = loginService.login(username, password);
        if (result) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            modelAndView.setViewName("list");

        } else {
            modelAndView.addObject("message", "登录失败");
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }

    @PostMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(request.getContextPath());
    }

    @GetMapping("/login/error")
    public ModelAndView error() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "无权限访问，请先登录");
        modelAndView.setViewName("login");
        return modelAndView;
    }
}
